//
//  YWCirculationDetailViewController.m
//  maintain
//
//  Created by Kyo on 16/6/23.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import "UITableView+FDTemplateLayoutCell.h"
#import "MJRefresh.h"
#import "Masonry.h"
#import "MBProgressHUD.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UIView+Extension.h"

#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWHandler.h"
#import "YWNoQrcodeRights.h"

#import "YWMissionManager.h"
#import "YWNavigationController.h"
#import "YWNotifyManager.h"
#import "YWTroubleMissionModel.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleManager.h"

#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWQrcodeManager.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWCirculationDetailViewController.h"
#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWReply.h"
#import "YWReplyManager.h"
#import "YYLabel.h"
#import "YWContactManager.h"
#import "YWEquipmentFieldRecord.h"
#import "YWEquipmentType.h"

#import "YWTroubleMissionFinishBillCell.h"
#import "YWNewCirculationButtonCell.h"
#import "YWAssignAndCancelPostTroubleCell.h"
#import "YWPostTroubleBillCell.h"
#import "YWTroubleMutableBIllCell.h"
#import "YWObserveTableViewCell.h"
#import "YWNewReplyTableViewCell.h"
#import "YWMeterReadingDetailRecordCell.h"

#import "YWDoTroubleMissionTableViewController.h"
#import "YWDoNoEquipmentTroubleMissionViewController.h"
#import "YWTroubleReplyTableViewController.h"
#import "YWWriteGrabTroubleInfoViewController.h"
#import "YWAssignTroubleMissionTableViewController.h"
#import "YWObserverTableViewController.h"
#import "YWSelectAtUserTableViewController.h"

@interface YWCirculationDetailViewController () <UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UIAlertViewDelegate,YWNewCirculationButtonCellDelegate,YWAssignAndCancelPostTroubleCellDelegate,YWPostTroubleBillCellDelegate,YWSelectAtUserTableViewDelegate,UITextFieldDelegate>{
    BOOL showTopLine;
    BOOL showBottomLine;
    BOOL canGrab;
    UIWebView *phoneCallWebView;
    NSString *replyContent;
}
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSMutableArray* dataSource;
@property (nonatomic, strong) NSMutableArray *circulationButtonArray;
@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) NSArray *circulationsArray;
@property (nonatomic, strong) YWLoginUser *currentUser;
@property (nonatomic, copy) NSString *fieldRecordContent;

@property (nonatomic, strong) UILabel *tableHeadLabel;
@property (nonatomic, strong) UIButton *noScanButton;
@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UIButton *doButton;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) UIView *replyView;//回复栏
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@end

@implementation YWCirculationDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"故障详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableHeaderView = self.tableHeadLabel;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    [self.navigationController.view addSubview:self.replyView];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshCirculationDetailVC) name:KPostRefreshCirculationDetailVCNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grabTroubleBillSuccess) name:KPostGrabTroubleBillSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grabTroubleBillFail:) name:KPostGrabTroubleBillFailNotification object:nil];
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(refreshTableView:)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (self.troubleMissionModel.trouble.troubleId>0) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
        // 马上进入刷新状态
        [self.tableView.mj_header beginRefreshing];
    }
}

-(void)setIsGrabTroubleBill:(BOOL)isGrabTroubleBill{
    _isGrabTroubleBill = isGrabTroubleBill;
    if (isGrabTroubleBill) {
        canGrab = YES;
    }
}

- (void)refreshCirculationDetailVC{
    _dataSource = nil;
    [self.tableView reloadData];
}

- (void)grabTroubleBillSuccess{
    canGrab = NO;
    _dataSource = nil;
    YWHandler *handler = [[YWHandler alloc] init];
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    handler.uniqueId = currentUser.uniqueId;
    handler.userName = currentUser.userName;
    handler.headIcon = currentUser.headIcon;
    handler.mobile = currentUser.mobile;
    self.troubleMissionModel.executor = handler;
    self.troubleMissionModel.troubleStatus = YWTroubleMissionStatusAssign;
    [self.tableView reloadData];
}

- (void)grabTroubleBillFail:(NSNotification*)noti{
    NSInteger statusCode = [noti.object integerValue];
    if (statusCode == 400 || statusCode == 304) {
        canGrab = NO;
    }else{
        canGrab = YES;
    }
    _dataSource = nil;
    [self.tableView reloadData];
    [self refreshTop];
}

- (void)refreshTableView:(NSNotification*)noti
{
    //完成任务的推送
    if ([noti.object isKindOfClass:[YWTroubleMissionModel class]]) {
        YWTroubleMissionModel* updateMission = (YWTroubleMissionModel*)noti.object;
        if (self.troubleMissionModel.trouble.troubleId == updateMission.trouble.troubleId) {
            self.troubleMissionModel = updateMission;
            _dataSource = nil;
            [self.tableView reloadData];
        }
    }
}

- (void)refreshTop{
    YWWeakSelf(weakSelf);
    [[YWCirculationManager shareManager] requestCirculationInfoWithTroubleId:weakSelf.troubleMissionModel.trouble.troubleId needTip:YES WithComplete:^(BOOL success){
        [weakSelf.tableView.mj_header endRefreshing];
        if (success) {
            YWTroubleMissionModel *troubleMission = [[YWTroubleMissionManager shareManager] troubleMissionModelWithTroubleId:weakSelf.troubleMissionModel.trouble.troubleId];
            if (troubleMission == nil) {//防止从报障进来，troublemission是nil的情况
                YWReportTroubleModel * reportTroulbe =
                [[YWReportTroubleManager shareManager] getOneReportTroubleWithTroubleId:weakSelf.troubleMissionModel.trouble.troubleId];
                troubleMission = reportTroulbe.troubleMission;
            }
            if (troubleMission.trouble.reporter==nil) {
                troubleMission.trouble.reporter = weakSelf.troubleMissionModel.trouble.reporter;
            }
            weakSelf.troubleMissionModel = troubleMission;
            if (weakSelf.isGrabTroubleBill && troubleMission.troubleStatus == YWTroubleMissionStatusUnAssign) {
                canGrab = YES;
            }
            weakSelf.dataSource = nil;
            [weakSelf.tableView reloadData];
        }
        //请求评论
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(weakSelf.troubleMissionModel.trouble.troubleId).stringValue type:YWReplyRelationTypeTrouble WithComplete:^(BOOL success) {
            weakSelf.dataSource = nil;
            weakSelf.replyArray = nil;
            [weakSelf.tableView reloadData];
        }];
    }];
}

- (UITableView*)tableView
{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        _tableView = tableView;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
        [_tableView registerClass:[YWPostTroubleBillCell class] forCellReuseIdentifier:YWPostTroubleBillCellIdentifier];
        [_tableView registerClass:[YWTroubleMissionFinishBillCell class] forCellReuseIdentifier:YWTroubleMissionFinishBillCellIdentifier];
        [_tableView registerClass:[YWTroubleMutableBIllCell class] forCellReuseIdentifier:YWTroubleMutableBIllCellIdentifier];
        [_tableView registerClass:[YWNewCirculationButtonCell class] forCellReuseIdentifier:YWNewCirculationButtonCellIdentifier];
        [_tableView registerClass:[YWAssignAndCancelPostTroubleCell class] forCellReuseIdentifier:YWAssignAndCancelPostTroubleCellIdentifier];
        [_tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
        [_tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
        [_tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
    }
    return _tableView;
}
- (NSString *)fieldRecordContent{
    if (!_fieldRecordContent) {
        //设备参数
        YWEquipmentTroubleRecord* troubleRecord = [[YWTroubleMissionManager shareManager] troubleRecordWithMissionId:_troubleMissionModel.trouble.troubleId];
        NSArray *fieldRecordArray = troubleRecord.equipmentFieldRecord;
        if (fieldRecordArray.count == 0) {
            fieldRecordArray = [[YWMissionManager shareManager] equipmentFieldRecordsWithUniqueTag:troubleRecord.uniqueTag maintenanceTypeId:YWMaintenanceTypeTrouble];
        }
        
        NSMutableString *contenStr = [NSMutableString string];
        if (fieldRecordArray.count) {
            __block NSString *str = nil;
            [fieldRecordArray enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldrecord, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx != 0) {
                    [contenStr appendString:@"\n"];
                }
                if (fieldrecord.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldOption.fieldOptionText?:@"未填写"];
                }else{
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldValue?:@"未填写"];
                }
                [contenStr appendString:str];
            }];
        }else{
            [contenStr appendString:@"无"];
        }
        _fieldRecordContent = [NSString stringWithFormat:@"%@",contenStr];
    }
    return _fieldRecordContent;
}
- (NSMutableArray*)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        if (self.troubleMissionModel) {
            NSMutableArray *firstArray = [NSMutableArray array];
            [firstArray addObject:self.troubleMissionModel];
            [_dataSource addObject:firstArray];
            if (self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish) {
                [firstArray addObject:self.troubleMissionModel];
            }
        }
        NSMutableArray *obserAndRepArray = [NSMutableArray array];
        [obserAndRepArray addObject:@""];//此为参与人row
        if (self.replyArray.count>0) {
            [obserAndRepArray addObject:@""];//“评论”row
            [obserAndRepArray addObjectsFromArray:self.replyArray];
        }
        [_dataSource addObject:obserAndRepArray];//参与人以及评论section
        
        _circulationsArray = [[YWCirculationManager shareManager] circulationInfoArrayWithTroubleId:self.troubleMissionModel.trouble.troubleId];
        if (_circulationsArray) {
            [_dataSource addObject:_circulationsArray];//流转section
        }
        //设置已读
        [[YWCirculationManager shareManager] updateReadStatusWithTroubleId:self.troubleMissionModel.trouble.troubleId];
        [self setUpDataSource];
    }
    if (!canGrab) {
        if (!_isNotShowHandleButton) {
            if (!_isFromMatchMissionVC) {
                if (self.troubleMissionModel.executor.uniqueId == self.currentUser.uniqueId && self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusAssign) {
                    if (self.troubleMissionModel.trouble.equipment.equipmentId == nil && self.troubleMissionModel.trouble.qrcodeId ==nil) {
                        if (![self.view.subviews containsObject:self.doButton]) {
                            [self.view addSubview:self.doButton];
                        }
                        if (self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish) {
                            self.doButton.backgroundColor = [UIColor lightGrayColor];}
                    }else{
                        if (![self.view.subviews containsObject:self.scanButton]) {
                            [self.view addSubview:self.noScanButton];
                            [self.view addSubview:self.scanButton];
                        }
                    }
                }else{
                    [_scanButton removeFromSuperview];
                    [_noScanButton removeFromSuperview];
                    [_doButton removeFromSuperview];
                }
            }else{
                if (self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish) {
                    self.doButton.backgroundColor = [UIColor lightGrayColor];
                }
                [self.view addSubview:self.doButton];
            }
        }else{
            [_scanButton removeFromSuperview];
            [_noScanButton removeFromSuperview];
            [_doButton removeFromSuperview];
        }
    }else{
        [_scanButton removeFromSuperview];
        [_noScanButton removeFromSuperview];
        [_doButton removeFromSuperview];
    }
    
    return _dataSource;
    
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:self.troubleMissionModel.trouble.troubleId andRelationType:YWReplyRelationTypeTrouble];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (NSMutableArray *)circulationButtonArray{
    if (!_circulationButtonArray) {
        _circulationButtonArray = [[NSMutableArray alloc] init];
    }
    return _circulationButtonArray;
}
- (void)setUpDataSource{
    YWLoginUser *currentUser = self.currentUser;
    [self.circulationButtonArray removeAllObjects];
    if (canGrab) {
        if (_troubleMissionModel.troubleStatus == YWTroubleMissionStatusUnAssign) {
            [self.circulationButtonArray addObject:@"抢单"];
        }
    }else{
        if (_troubleMissionModel.uploadFail) {
            _isNotShowHandleButton = YES;
        }
        if (!_isNotShowHandleButton) {
            if (!self.isFromMatchMissionVC) {
                if (_troubleMissionModel.troubleStatus == YWTroubleMissionStatusAssign) {
                    if (_troubleMissionModel.creator.uniqueId == currentUser.uniqueId) {//currentUser.isTroubleServer &&
                        [self.circulationButtonArray addObject:@"撤回"];
                    }else if (_troubleMissionModel.creator.uniqueId != currentUser.uniqueId && _troubleMissionModel.executor.uniqueId == currentUser.uniqueId){
                        [self.circulationButtonArray addObject:@"退回"];
                    }
                }else if (_troubleMissionModel.troubleStatus == YWTroubleMissionStatusUnAssign){
                    if (self.currentUser.isTroubleServer && _troubleMissionModel.trouble.reporter.uniqueId == self.currentUser.uniqueId) {
                        [self.circulationButtonArray addObject:@"分配和撤回报障"];
                    }else if (currentUser.isTroubleServer){
                        [self.circulationButtonArray addObject:@"分配"];
                    }else if (_troubleMissionModel.trouble.reporter.uniqueId == currentUser.uniqueId){
                        [self.circulationButtonArray addObject:@"撤回报障"];
                    }
                }else{
                    [self.circulationButtonArray removeAllObjects];
                }
            }
        }
    }
    
    __block NSUInteger isLastAssignIdx = 0;
    [_circulationsArray enumerateObjectsUsingBlock:^(YWCirculationInfo*  _Nonnull circulationInfo, NSUInteger idx, BOOL * _Nonnull stop) {
        if (circulationInfo.type == YWCirculationInfoTypeAssignTroubleMission){
            isLastAssignIdx = idx;
            *stop = YES;
        }
    }];
    if (_circulationsArray.count) {
        YWCirculationInfo *circulationInfo = isLastAssignIdx>0?_circulationsArray[isLastAssignIdx]:nil;
        circulationInfo.isLastAssignBill = circulationInfo?YES:NO;
    }
    if (_circulationButtonArray.count) {
        [_dataSource addObject:_circulationButtonArray];
    }
    
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionCount = self.dataSource[section];
    return sectionCount.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            YWPostTroubleBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleBillCellIdentifier];
            [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
            return cell;
            
        }else if (indexPath.row == 1) {
            YWTroubleMissionFinishBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier];
            [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
            return cell;
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.troubleMissionModel = self.troubleMissionModel;//参与人cell
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"评论%@:",count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.dataSource[indexPath.section][indexPath.row];
            cell.reply = reply;
            return cell;
        }
    }else if (indexPath.section == 2) {
        YWTroubleMutableBIllCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMutableBIllCellIdentifier];
//        上下线的显示
        NSArray *rowArray = self.dataSource[indexPath.section];
        cell.isFirstRow = NO;
        if (indexPath.row == 0) {
            showTopLine = NO;
            showBottomLine = YES;
            cell.isFirstRow = YES;
        } else if (indexPath.row == (rowArray.count - 1)){
            showTopLine = YES;
            showBottomLine = NO;
        } else {
            showTopLine = YES;
            showBottomLine = YES;
        }
        UIView *topLine = (UILabel *)[cell viewWithTag:KTopLineTag];
        UIView *bottomLine = (UILabel *)[cell viewWithTag:KBottomLineTag];
        topLine.hidden = !showTopLine;
        bottomLine.hidden = !showBottomLine;
//        cell赋值
        [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        NSString *buttonTitle = self.circulationButtonArray[indexPath.row];
        if ([buttonTitle isEqualToString:@"分配和撤回报障"]) {
            YWAssignAndCancelPostTroubleCell *cell = [tableView dequeueReusableCellWithIdentifier:YWAssignAndCancelPostTroubleCellIdentifier];
            cell.delegate = self;
            return cell;
        }else{
            YWNewCirculationButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNewCirculationButtonCellIdentifier];
            cell.delegate = self;
            
            cell.buttonTitle = buttonTitle;
            return cell;
        }
    }
    return [[UITableViewCell alloc] init];
}
#pragma configure cell
- (void)configurePostTroubleBillCell:(YWPostTroubleBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.delegate = self;
    cell.troubleMissionModel = self.troubleMissionModel;
}

- (void)configureTroubleFinishBillCell:(YWTroubleMissionFinishBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.troubleMissionModel = self.troubleMissionModel;
    cell.fieldRecordContent = self.fieldRecordContent;
}
- (void)configureTroubleMutableBIllCell:(YWTroubleMutableBIllCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWCirculationInfo *circulationInfoc = self.dataSource[indexPath.section][indexPath.row];
    cell.troubleMissionModel = self.troubleMissionModel;
    cell.circulationInfo = circulationInfoc;
}

#pragma mark - UITableViewDataDelegate mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section == 0) {
//        if (indexPath.row == 0) {
//            return [tableView fd_heightForCellWithIdentifier:YWPostTroubleBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroubleBillCell *cell) {
//                [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
//            }];
//            
//        }else if (indexPath.row == 1) {
//            return [tableView fd_heightForCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMissionFinishBillCell *cell) {
//                [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
//            }];
//        }
//    } else if (indexPath.section == 1) {
//        return [tableView fd_heightForCellWithIdentifier:YWTroubleMutableBIllCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMutableBIllCell *cell) {
//            [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        NSString *buttonTitle = self.circulationButtonArray[indexPath.row];
//        if ([buttonTitle isEqualToString:@"分配和撤回报障"]) {
//            return kButtonH*2+10*3;
//        }else{
//            return kButtonH+10*2;
//        }
//    }
//    return 0.0;
    
//    if (indexPath.section==0 && indexPath.section==1) {
//        return UITableViewAutomaticDimension;
//    }else{
//        NSString *buttonTitle = self.circulationButtonArray[indexPath.row];
//        if ([buttonTitle isEqualToString:@"分配和撤回报障"]) {
//            return kButtonH*2+10*3;
//        }else{
//            return kButtonH+10*2;
//        }
//    }
//}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? 0 : 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == 0 ? 23 : 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section!=0) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWCirculatonDetailVCForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor whiteColor];
        //评论
        UILabel *replyLabel = [[UILabel alloc] init];
        replyLabel.textAlignment = NSTextAlignmentLeft;
        replyLabel.textColor = [UIColor customTextGrayColor];
        replyLabel.tag = 2006;
        replyLabel.font = KSmallContentFont;
        replyLabel.userInteractionEnabled = YES;
        [replyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyLabel];
        
        UIImageView *replyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"remind_replyIcon"]];
        replyImageView.tag = 2006;
        replyImageView.userInteractionEnabled = YES;
        [replyImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyImageView];
        
        [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(replyImageView.mas_top);
            make.left.mas_equalTo(replyImageView.mas_right).offset(8);
            make.right.mas_equalTo(headerView.mas_right).offset(-8);
            make.bottom.mas_equalTo(replyImageView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        //参与者
        UILabel *observerLabel = [[UILabel alloc] init];
        observerLabel.textAlignment = NSTextAlignmentLeft;
        observerLabel.textColor = [UIColor customTextGrayColor];
        observerLabel.tag = 2007;
        observerLabel.font = KSmallContentFont;
        observerLabel.userInteractionEnabled = YES;
        [observerLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerLabel];
        
        UIImageView *observerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_invite"]];
        observerView.tag = 2007;
        observerView.userInteractionEnabled = YES;
        [observerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerView];
        
        [observerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [observerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(observerView.mas_top);
            make.left.mas_equalTo(observerView.mas_right).offset(8);
            make.right.mas_equalTo(replyImageView.mas_left).offset(-8);
            make.bottom.mas_equalTo(observerView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        
        //分享
        UILabel *shareLabel = [[UILabel alloc] init];
        shareLabel.textAlignment = NSTextAlignmentLeft;
        shareLabel.textColor = [UIColor customTextGrayColor];
        shareLabel.tag = 2008;
        shareLabel.font = KSmallContentFont;
        shareLabel.userInteractionEnabled = YES;
        [shareLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleShareLabelTapEvent:)]];
        [headerView addSubview:shareLabel];
        
        UIImageView *shareView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_share"]];
        shareView.tag = 2008;
        shareView.userInteractionEnabled = YES;
        [shareView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleShareLabelTapEvent:)]];
        [headerView addSubview:shareView];
        [shareView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [shareLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(shareView.mas_top);
            make.left.mas_equalTo(shareView.mas_right).offset(8);
            make.right.mas_equalTo(observerView.mas_left).offset(-8);
            make.bottom.mas_equalTo(shareView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];

        //等待维修的时间
        UILabel *difTimeLabel = [[UILabel alloc] init];
        difTimeLabel.textAlignment = NSTextAlignmentLeft;
        difTimeLabel.textColor = [UIColor customTextGrayColor];
        difTimeLabel.tag = 2009;
        difTimeLabel.font = KSmallContentFont;
        [headerView addSubview:difTimeLabel];
        
        UIImageView *difView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_wait"]];
        difView.tag = 2009;
        [headerView addSubview:difView];
        [difView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(headerView);
            make.left.mas_equalTo(headerView).offset(8);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        
        [difTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(difView.mas_top);
            make.left.mas_equalTo(difView.mas_right).offset(5);
//            make.right.mas_equalTo(difView.mas_left).offset(-15);
            make.bottom.mas_equalTo(difView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@100);//这个约束要改
        }];
    }
    UILabel* label = [headerView viewWithTag:2006];
    label.text = @"评论";
//    NSInteger replyCount = 0;
    //    评论
//    if (_troubleMissionModel.trouble.troubleId>0) {
//        replyCount = [[YWReplyManager shareManager] replysCountWithtRelationId:_troubleMissionModel.trouble.troubleId relationType:YWReplyRelationTypeTrouble];
//    }
//    label.text = [@(replyCount) stringValue];
    
    //参与者
    label = [headerView viewWithTag:2007];
//    NSInteger reporterId = self.troubleMissionModel.trouble.reporter.uniqueId;
//    NSInteger creatorId = self.troubleMissionModel.creator.uniqueId;
//    NSInteger executorId = self.troubleMissionModel.executor.uniqueId;
//    NSInteger showCount = 0;
//    NSMutableArray *idMutArray = [NSMutableArray array];
//    if (reporterId>0) {
//        showCount++;
//        [idMutArray addObject:@(reporterId)];
//    }
//    if (creatorId>0 && creatorId!=reporterId) {
//        showCount++;
//        [idMutArray addObject:@(creatorId)];
//    }
//    if (executorId>0 && executorId!=reporterId && executorId!=creatorId) {
//        showCount++;
//        [idMutArray addObject:@(executorId)];
//    }
//    NSInteger observerCount = self.troubleMissionModel.trouble.observers.count;
//    if (observerCount) {
//        for (id object in idMutArray) {
//            NSInteger uniqueId = [object integerValue];
//            NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
//            NSArray *array = [[self.troubleMissionModel.trouble.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
//            if (array.count==1) {
//                observerCount--;
//            }
//            if (observerCount==0) {
//                break;
//            }
//        }
//        showCount = showCount + observerCount;
//    }
//    label.text = [@(showCount) stringValue];
    label.text = @"邀请";
    //分享
    label = [headerView viewWithTag:2008];
    label.text = @"分享";
    //等待时间
    label = [headerView viewWithTag:2009];
    if (self.troubleMissionModel.troubleStatus == YWTroubleMissionStatusFinish){
        NSTimeInterval waitTime = (self.troubleMissionModel.updateTime - self.troubleMissionModel.trouble.reportTime)/1000;
        label.text = [self backWaitTimeWithTimeInterval:waitTime];
    }else{
        NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
        NSTimeInterval waitTime = currentTime - (self.troubleMissionModel.trouble.reportTime)/1000;
        label.text = [self backWaitTimeWithTimeInterval:waitTime];
    }
    return headerView;
}

- (NSString*)backWaitTimeWithTimeInterval:(NSTimeInterval)waitTime{
    NSTimeInterval aDay = 3600*24;
    NSTimeInterval aHour = 3600;
    if (waitTime>aDay) {
        int days = ((int)waitTime)/(3600*24);
        int hours = ((int)waitTime)%(3600*24)/3600;
        NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];
        return dateContent;
    }else if (waitTime<aDay && waitTime>aHour){
        int hours = ((int)waitTime)%(3600*24)/3600;
        int minutes = ((int)waitTime)%(3600*24)%3600/60;
        NSString *dateContent=[[NSString alloc] initWithFormat:@"%i小时%i分",hours,minutes];
        return dateContent;
    }else{
        int minutes = ((int)waitTime)%(3600*24)%3600/60;
        NSString *dateContent=[[NSString alloc] initWithFormat:@"%i分",minutes];
        return dateContent;
    }
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && !_isGrabTroubleBill && !_isNotShowHandleButton) {
        YWTroubleReplyTableViewController *troubleReplyVC = [[YWTroubleReplyTableViewController alloc] init];
        troubleReplyVC.troubleMissionModel = self.troubleMissionModel;
        [self.navigationController pushViewController:troubleReplyVC animated:YES];
    }
}

#pragma mark - YWCirculationButtonCellDelegate
- (void)clickCirculationButtonEventWithTitle:(NSString *)buttonTitle{
    if ([buttonTitle isEqualToString:@"撤回"]) {
        [self cancelTroubleMission];
    }else if ([buttonTitle isEqualToString:@"退回"]){
        [self rejectTroubleMission];
    }else if ([buttonTitle isEqualToString:@"分配"]){
        [self assignTroubleMission];
    }else if ([buttonTitle isEqualToString:@"撤回报障"]){
        [self clickCancelPostTrouble];
    }else if ([buttonTitle isEqualToString:@"抢单"]){
        [self grabTroubleBillEvent];
    }
}

#pragma mark - YWAssignAndCancelPostTroubleCellDelegate
- (void)clickAssignOrCancelPostTroubleButtonEventWithTitle:(NSString *)buttonTitle{
    if ([buttonTitle isEqualToString:@"分配"]){
        [self assignTroubleMission];
    }else if ([buttonTitle isEqualToString:@"撤回报障"]){
        [self clickCancelPostTrouble];
    }
}

- (void)assignTroubleMission{
    YWAssignTroubleMissionTableViewController * detailVC = [[YWAssignTroubleMissionTableViewController alloc] init];
    detailVC.troubleMissionModel = self.troubleMissionModel;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

- (void)clickCancelPostTrouble
{
    //撤回报障
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"撤回报障备注" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"撤回报障的原因或备注";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        NSString *cancelNote = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (cancelNote.length>100) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        }else if ([YWCommonTool isContainsEmoji:cancelNote]) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        }else{
            [[YWCirculationManager shareManager] cancelPostTroubleWithTroubleId:self.troubleMissionModel.trouble.troubleId cancelNote:cancelNote WithComplete:^(NSInteger statusCode) {
                [self.HUD hide:YES];
                if (statusCode==200) {
                    _troubleMissionModel.troubleStatus = YWTroubleMissionStatusCancelPostTrouble;
                    
                    [YWCommonTool showTextHUDWithContent:@"撤回报障成功"];
                    _dataSource = nil;
                    [self.tableView reloadData];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostCirculationHandlerNotification object:nil];
                }else if (statusCode == 400){
//                    [YWCommonTool showTextHUDWithContent:@"故障已分配,无法撤回"];
                    [self refreshTop];
                }
//                else{
//                    [YWCommonTool showTextHUDWithContent:@"撤回报障失败,请稍后再试"];
//                }
            }];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)cancelTroubleMission{
    //撤回维修
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定撤回该任务?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [[YWCirculationManager shareManager] cancelTroubleMissionWithTrouble:self.troubleMissionModel WithComplete:^(NSInteger statusCode) {
            [self.HUD hide:YES];
            if (statusCode==200) {
                _troubleMissionModel.troubleStatus = YWTroubleMissionStatusUnAssign;
                _troubleMissionModel.executor = nil;
                _troubleMissionModel.updateTime = [[NSDate date] timeIntervalSince1970];

                if (_isGrabTroubleBill) {
                    canGrab = YES;
                }
                [YWCommonTool showTextHUDWithContent:@"撤回维修任务成功"];
                _dataSource = nil;
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:KPostCirculationHandlerNotification object:nil];
            }else if (statusCode ==400){
//                [YWCommonTool showTextHUDWithContent:@"维修任务只能在分配状态下才能由分配人取消"];
                [self refreshTop];
            }
//            else{
//                [YWCommonTool showTextHUDWithContent:@"撤回维修任务失败,请稍后重试"];
//            }
        }];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)rejectTroubleMission{
    //退回
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退回任务备注" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"退回任务的原因或备注";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        NSString *rejectReason = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (rejectReason.length>100) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        }else if ([YWCommonTool isContainsEmoji:rejectReason]) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        }else{
            [[YWCirculationManager shareManager] rejectTroubleMissionWithTrouble:self.troubleMissionModel rejectReason:rejectReason WithComplete:^(NSInteger statusCode) {
                [self.HUD hide:YES];
                if (statusCode==200) {
                    _troubleMissionModel.troubleStatus = YWTroubleMissionStatusUnAssign;
                    _troubleMissionModel.executor = nil;
                    _troubleMissionModel.updateTime = [[NSDate date] timeIntervalSince1970];
                    if (_isGrabTroubleBill) {
                        canGrab = YES;
                    }                    
                    
                    [YWCommonTool showTextHUDWithContent:@"退回任务成功 "];
                    _dataSource = nil;
                    [self.tableView reloadData];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostCirculationHandlerNotification object:nil];
                }else if (statusCode == 400){
//                    [YWCommonTool showTextHUDWithContent:@"维修任务只能在分配状态下才能由执行人退回"];
                    [self refreshTop];
                }
//                else{
//                    [YWCommonTool showTextHUDWithContent:@"退回失败,请稍后重试"];
//                }
            }];
        }
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)handleDoBtnEvent:(id)sender{
    if (self.troubleMissionModel.troubleStatus >=YWTroubleMissionStatusFinish) {
        [YWCommonTool showTextHUDWithContent:@"任务已完成"];
        return;
    }
//    if (self.troubleMission.equipmentId == nil && self.troubleMission.qrcodeId == nil) {
//        YWDoNoEquipmentTroubleMissionViewController *doNoEquipmentVC = [[YWDoNoEquipmentTroubleMissionViewController alloc] init];
//        doNoEquipmentVC.troubleMission = self.troubleMission;
//        [self.navigationController pushViewController:doNoEquipmentVC animated:YES];
//    }else{
        YWDoTroubleMissionTableViewController* doTroubleVC = [[YWDoTroubleMissionTableViewController alloc] init];
        doTroubleVC.troubleMissionModel = self.troubleMissionModel;
        [self.navigationController pushViewController:doTroubleVC animated:YES];
//    }
}

- (void)handleScanBtnEvent:(id)sender{
    YWTroubleMissionModel* weakMission = self.troubleMissionModel;
    if (self.troubleMissionModel.trouble.qrcodeId.length == 0 && self.troubleMissionModel.trouble.equipment.qrcodeId.length==0) {
        YWDoTroubleMissionTableViewController *doTroubleVC = [[YWDoTroubleMissionTableViewController alloc] init];
        doTroubleVC.troubleMissionModel = self.troubleMissionModel;
        [self.navigationController pushViewController:doTroubleVC animated:YES];
    }else{
        [[YWQrcodeManager shareManager] clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                    YWMissionScanQrcodeStatus missionScanQrcodeStatus = [[YWMissionManager shareManager] judgeScanMatchMission:weakMission qrcodeId:qrcodeId orNoScanQrcodeLocationId:0];
                    if (missionScanQrcodeStatus == YWMissionScanQrcodeStatusMatch) {
//                        if (self.troubleMission.equipmentId==nil) {
//                            YWDoNoEquipmentTroubleMissionViewController *doNoEquipmentVC = [[YWDoNoEquipmentTroubleMissionViewController alloc] init];
//                            doNoEquipmentVC.troubleMission = self.troubleMission;
//                            [self.navigationController pushViewController:doNoEquipmentVC animated:YES];
//                        }else{
                            YWDoTroubleMissionTableViewController *doTroubleVC = [[YWDoTroubleMissionTableViewController alloc] init];
                            doTroubleVC.troubleMissionModel = weakMission;
                            [self.navigationController pushViewController:doTroubleVC animated:YES];
//                        }
                        
                    }else {
                        YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
                        senmVC.showContent = @"扫描的二维码无匹配的任务，请扫描其它的二维码";
                        [self.navigationController pushViewController:senmVC animated:YES];
                    }
                }];
            });
        }];
    }
}

- (void)clickPostTroubleMobileWithNumber:(NSString *)mobileNumber{
    if (mobileNumber.length) {
        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",mobileNumber]];
        if ( !phoneCallWebView ) {
            phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
        });
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有此联系人的电话号码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)handleNoScanBtnEvent:(id)sender{
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeFixTroubleKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"无码工作已被管理员禁止" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        YWDoTroubleMissionTableViewController *doTroubleVC = [[YWDoTroubleMissionTableViewController alloc] init];
        doTroubleVC.troubleMissionModel = self.troubleMissionModel;
        [self.navigationController pushViewController:doTroubleVC animated:YES];
    }
}

- (void)grabTroubleBillEvent{
    YWWriteGrabTroubleInfoViewController *grabTroubleBillVC = [[YWWriteGrabTroubleInfoViewController alloc] init];
    grabTroubleBillVC.reportTroubleModel = self.troubleMissionModel.trouble;
    YWNavigationController* nav = [[YWNavigationController alloc] initWithRootViewController:grabTroubleBillVC];
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark - 评论、邀请、分享等响应事件
- (void)handleReplyLabelTapEvent:(id)sender{
    [self.textField becomeFirstResponder];
}

- (void)handleObserverLabelTapEvent:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters = self.troubleMissionModel.creator?@[self.troubleMissionModel.creator]:nil;
    observerVC.executors = self.troubleMissionModel.executor?@[self.troubleMissionModel.executor]:nil;
    observerVC.reporters = self.troubleMissionModel.trouble.reporter?@[self.troubleMissionModel.trouble.reporter]:nil;
    observerVC.observers = self.troubleMissionModel.trouble.observers;
    observerVC.relationId = [@(self.troubleMissionModel.trouble.troubleId) stringValue];
    observerVC.type = YWReplyRelationTypeTrouble;
    [self.navigationController pushViewController:observerVC animated:YES];
}

- (void)handleShareLabelTapEvent:(id)sender{
    NSString *textToShare = @"要分享的文本内容";
    //UIImage *imageToShare = [UIImage imageNamed:@"iosshare.jpg"];
    NSURL *urlToShare = [NSURL URLWithString:@"http://www.baidu.com"];
    
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    NSMutableArray *excludedActivityTypes =  [NSMutableArray arrayWithArray:@[UIActivityTypeAirDrop, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeMail, UIActivityTypePostToTencentWeibo, UIActivityTypeSaveToCameraRoll, UIActivityTypeMessage, UIActivityTypePostToTwitter]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        //YWLog(@"%@  ----   %@", activityType, returnedItems);
        if (completed) {
            //YWLog(@"completed");
        }else{
            //YWLog(@"failed");
        }
    };
}


- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        //[scanButton setImage:[UIImage imageNamed:@"repair_normal"] forState:UIControlStateNormal];
        //scanButton.layer.masksToBounds = YES;
        [button setTitle:@"扫码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(handleScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"无码" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

- (UIButton *)doButton{
    if (!_doButton) {
        UIButton* doButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [doButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [doButton setBackgroundColor:[UIColor customBlueColor]];
        [doButton setTitle:@"做任务" forState:UIControlStateNormal];
        [doButton addTarget:self action:@selector(handleDoBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        doButton.frame = CGRectMake(0, SCREEN_HEIGHT-64-kButtonH, SCREEN_WIDTH, kButtonH);
        _doButton = doButton;
    }
    return _doButton;
}

-(UILabel *)tableHeadLabel{
    if (!_tableHeadLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.font = KTitleFont;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        label.attributedText = [YWCommonTool labelAttributedStringWithFristStr:@"编号: " secondStr:self.troubleMissionModel.trouble.troubleSequence?:@"无" secondColor:[UIColor customYellowColor]];
        _tableHeadLabel = label;
    }
    return _tableHeadLabel;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}
- (YWLoginUser *)currentUser{
    if (!_currentUser) {
        _currentUser = [YWLoginTool loginUser];
    }
    return _currentUser;
}

- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        _replyView.hidden = YES;
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40-15, 40)];
    self.textField.placeholder = @"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, 40, 40);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    if (self.troubleMissionModel.creator) {
        [allUser addObject:self.troubleMissionModel.creator];
    }
    if (self.troubleMissionModel.executor) {
        [allUser addObject:self.troubleMissionModel.executor];
    }
    if (self.troubleMissionModel.trouble.reporter) {
        [allUser addObject:self.troubleMissionModel.trouble.reporter];
    }
    //observer
    [allUser addObjectsFromArray:self.troubleMissionModel.trouble.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请填写回复内容"];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:@"回复内容不超过100字"];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    replyContent = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:@"回复成功"];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            _dataSource = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _troubleMissionModel.trouble.troubleId;
    reply.relationType = YWReplyRelationTypeTrouble;
    reply.content = replyContent;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.troubleMissionModel.trouble.observers];
        [tempArray addObject:handler];
        self.troubleMissionModel.trouble.observers = [NSArray arrayWithArray:tempArray];
        _replyArray = nil;
        _dataSource = nil;
        [self.tableView reloadData];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.troubleMissionModel.trouble.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.troubleMissionModel.trouble.observers];
            [tempArray removeObject:handler];
            self.troubleMissionModel.trouble.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
